package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.repository.ITravelCommentRepository;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class TravelCommentServiceImpl implements ITravelCommentService {


    @Autowired
    private ITravelCommentRepository travelCommentRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 添加攻略评论实现
     * @param travelComment
     */
    @Override
    public TravelComment save(TravelComment travelComment) {
        if(!StringUtils.hasLength(travelComment.getId())){
            travelComment.setCreateTime(new Date());
        }
        String refId = travelComment.getRefComment().getId();
        if (StringUtils.hasLength(refId)){
            TravelComment refComment = travelCommentRepository.findById(refId).get();
            travelComment.setRefComment(refComment);
        }
        travelCommentRepository.save(travelComment);
        return travelComment;
    }

    /**
     * 评论列表+分页
     * @param qo
     * @return
     */
    @Override
    public Page<TravelComment> query(TravelCommentQuery qo) {

        //repository 和 mongodbtemplate 都不能直接得到page对象

        //拼接条件
        Query query = new Query();
        if(qo.getTravelId()!=-1){
            Criteria criteria = Criteria.where("travelId").is(qo.getTravelId());
            query.addCriteria(criteria);
        }
        //获取总数
        long total = mongoTemplate.count(query, TravelComment.class);
        if(total == 0){
            return Page.empty();
        }
        //分页
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                Sort.Direction.DESC, "createTime");
        List<TravelComment> commentList = mongoTemplate.find(query, TravelComment.class);

        return new PageImpl<>(commentList,pageable,total);
    }

    @Override
    public Long getCount(Long travelId) {
        //拼接条件
        Query query = new Query();
        if(travelId != null){
            Criteria criteria = Criteria.where("travelId").is(travelId);
            query.addCriteria(criteria);
        }
        //获取总数
        return mongoTemplate.count(query, TravelComment.class);
    }
}
